# users/forms.py
from django import forms
from .models import User


class AvatarUpdateForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['avatar']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['avatar'].widget.attrs.update({
            'class': 'form-control',
            'accept': 'image/jpeg,image/png,image/gif'
        })

    def clean_avatar(self):
        avatar = self.cleaned_data.get('avatar')
        if avatar:
            # 头像文件大小限制（5MB）
            if avatar.size > 5 * 1024 * 1024:
                raise forms.ValidationError("头像文件大小不能超过 5MB")

            # 验证文件类型
            valid_extensions = ['jpg', 'jpeg', 'png']
            extension = avatar.name.split('.')[-1].lower()
            if extension not in valid_extensions:
                raise forms.ValidationError("请上传 JPG, PNG 或 PNG 格式的图片")

        return avatar